package fivestar.model.dao.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import fivestar.model.dao.AddressDao;
import fivestar.model.entity.Address;
import fivestar.util.HibernateUtil;

public class AddressDaoHibernate implements AddressDao {

	Session session = null;
	Transaction tx = null;
	
	@Override
	public void create(Address address) throws RuntimeException {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			session.save(address);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}

	}

	@Override
	public void delete(Address address) throws RuntimeException {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			session.delete(address);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		
	}

	@Override
	public void update(Address address) throws RuntimeException {
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			session.update(address);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}		
	}

	@Override
	public Address find(int id) throws RuntimeException {
		Address address = null;
		session = HibernateUtil.getSessionFactory().openSession();
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("from Address where addressId=:addressId");
			query.setInteger("addressId", id);
			address = (Address) query.uniqueResult();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.flush();
			session.close();
		}
		return address;
	}

	@Override
	public List<String> findAll(String address) throws RuntimeException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Short findID(Address address) throws RuntimeException {      
        return null;
    }

}
